package com.pybox.service;

import com.pybox.dto.TOptionLogsDto;
import com.pybox.entity.TOptionLogs;
import com.pybox.repository.TOptionLogsRepository;
import com.pybox.spec.TOptionLogsSpec;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* 描述：TOptionLogs Service
* @author wuyingkai
* @date 2018-09-15
*/

@Service
@Transactional
public class TOptionLogsService {

    @Autowired
    private TOptionLogsRepository repository;

    /**
     * 创建TOptionLogs
     *
     * @param source
     * @return
     */
    public boolean create(TOptionLogsDto source){

        TOptionLogs target = new TOptionLogs();
        BeanUtils.copyProperties(source, target);
        repository.save(target);

        return true;

    }

    /**
     * 根据ID删除TOptionLogs
     *
     * @param id
     * @return
     */
    public boolean delete(Integer id){

        repository.delete(id);

        return true;

    }

    /**
     * 更新TOptionLogs
     *
     * @param id
     * @param source
     * @return
     */
    public boolean update(Integer id, TOptionLogsDto source){

        TOptionLogs exist = repository.findOne(id);
        if (null == exist){
            throw new RuntimeException("记录不存在");
        }

        BeanUtils.copyProperties(source, exist, new String[]{"id"});
        repository.save(exist);

        return true;

    }

    /**
     * 根据ID查询TOptionLogs
     *
     * @param id
     * @return
     */
    public TOptionLogsDto detail(Integer id){

        TOptionLogs exist = repository.findOne(id);
        if (null == exist){
            throw new RuntimeException("记录不存在");
        }

        TOptionLogsDto target = new TOptionLogsDto();
        BeanUtils.copyProperties(exist, target);

        return target;

    }

    /**
     * 分页查询查询TOptionLogs
     *
     * @param pageNo
     * @param pageSize
     * @param paramMap
     * @return
     */
    public Page<TOptionLogsDto> page(Integer pageNo, Integer pageSize, Map<String, String> paramMap){

        Pageable pageable = new PageRequest(pageNo - 1, pageSize);
        Page<TOptionLogs> data = repository.findAll(new TOptionLogsSpec(paramMap), pageable);

        List<TOptionLogsDto> list = new ArrayList<>();
        for (TOptionLogs obj : data.getContent()) {
            TOptionLogsDto dto = new TOptionLogsDto();
            BeanUtils.copyProperties(obj, dto);
            list.add(dto);
        }

        Page<TOptionLogsDto> page = new PageImpl<>(list, pageable, data.getTotalElements());

        return page;

    }
}